package com.tencent.iov.cowin.befsale.clue.service.clue.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.software.boot.common.entity.Response;
import com.software.boot.common.exception.BusinessException;
import com.software.boot.common.model.dao.PageRequest;
import com.software.boot.common.model.dao.PageResponse;
import com.software.boot.common.util.BeanUtil;
import com.software.boot.common.util.DateUtil;
import com.software.boot.common.util.EmptyUtils;
import com.software.boot.common.util.StringUtil;
import com.software.boot.common.util.ValidateUtils;
import com.software.common.enums.DeleteEnum;
import com.tencent.iov.cowin.befsale.clue.controller.clue.assembler.ClueAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.clue.assembler.ClueDayStatsAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.clue.assembler.ClueInitialAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.clue.assembler.ClueIntentionAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.clue.assembler.ClueIntentionVehicleAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.request.AccessAddClueInitialRequest;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.request.AddClueInitialAfterWashRequest;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.request.AddClueIntentionRequest;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.request.AddClueIntentionVehicleRequest;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.request.AddClueRequest;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.request.ClueFollowUpRequest;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.response.ThirdCreateClueInitialResponse;
import com.tencent.iov.cowin.befsale.clue.controller.cus.assembler.CustomerExtAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.cus.assembler.OemCustomerAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.cus.assembler.OemCustomerFollowPlanAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.cus.assembler.OemCustomerFollowRecordAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.AddCustomerExtRequest;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.AddCustomerFollowRecordRequest;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.AddOemCustomerFollowPlanRequest;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.AddOemCustomerFollowRecordRequest;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.AddOemCustomerRequest;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.CustomerSourceInfo;
import com.tencent.iov.cowin.befsale.clue.dao.http.crm.request.SyncCrmCreateClueRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.iam.IamIncCenterClient;
import com.tencent.iov.cowin.befsale.clue.dao.http.iam.request.CenterPhoneRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.iam.response.CenterPhoneResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.MdQueryClient;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.request.QueryAreaRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.request.QueryCustomerBaseRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.request.QueryDealerRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.request.QueryUserRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.request.QueryVehicleModelRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.request.QueryVehicleSeriesRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.request.SecondaryDealerRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.response.AreaResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.response.CustomerBaseResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.response.DealerResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.response.EmployeeResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.response.SecondaryDealerResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.response.VehicleModelResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.response.VehicleSeriesResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.tenant.TenantClient;
import com.tencent.iov.cowin.befsale.clue.dao.http.tenant.request.QueryDictionariesRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.tenant.response.DictionariesResponse;
import com.tencent.iov.cowin.befsale.clue.dao.kafka.response.ClueInitialCrm;
import com.tencent.iov.cowin.befsale.clue.dao.redis.CommRedisDao;
import com.tencent.iov.cowin.befsale.clue.domain.clue.po.Clue;
import com.tencent.iov.cowin.befsale.clue.domain.clue.po.ClueInitial;
import com.tencent.iov.cowin.befsale.clue.domain.clue.po.ClueIntentionVehicle;
import com.tencent.iov.cowin.befsale.clue.repository.clue.ClueInitialManager;
import com.tencent.iov.cowin.befsale.clue.service.clue.ClueInitialIntentionVehicleService;
import com.tencent.iov.cowin.befsale.clue.service.clue.ClueInitialService;
import com.tencent.iov.cowin.befsale.clue.service.clue.ClueLogService;
import com.tencent.iov.cowin.befsale.clue.service.clue.ClueService;
import com.tencent.iov.cowin.befsale.clue.service.clue.ClueSyncService;
import com.tencent.iov.cowin.befsale.clue.service.clue.CrmService;
import com.tencent.iov.cowin.befsale.clue.service.cus.DealerCustomerFollowRecordService;
import com.tencent.iov.cowin.befsale.clue.value.enums.ClueErrorEnum;
import com.tencent.iov.cowin.befsale.clue.value.enums.ClueStatsEnum;
import com.tencent.iov.cowin.befsale.clue.value.enums.CustomerStatusEnum;
import com.tencent.iov.cowin.befsale.clue.value.enums.DealerFollowStatusEnum;
import com.tencent.iov.cowin.befsale.clue.value.enums.DeletedEnum;
import com.tencent.iov.cowin.befsale.clue.value.enums.FollowRecordSecondStatusEnum;
import com.tencent.iov.cowin.befsale.clue.value.enums.FollowRecordStatusEnum;
import com.tencent.iov.cowin.befsale.clue.value.enums.GenderEnum;
import com.tencent.iov.cowin.befsale.clue.value.enums.InitalSendTypeEnum;
import com.tencent.iov.cowin.befsale.clue.value.enums.InitialCleanTypeEnum;
import com.tencent.iov.cowin.befsale.clue.value.enums.InitialSourceFirstEnum;
import com.tencent.iov.cowin.befsale.clue.value.enums.InitialSourceSecondEnum;
import com.tencent.iov.cowin.befsale.clue.value.enums.InitialStatusEnum;
import com.tencent.iov.cowin.befsale.clue.value.enums.StatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.session.RowBounds;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Describe: 线索源信息表_Service实现层
 * @author: whp
 * @created: 2021-12-21 16:16:11
 * @version: 1.0
 */
@Service
@Slf4j
public class ClueInitialServiceImpl implements ClueInitialService {

    @Autowired
    private ClueInitialManager clueInitialManager;

    @Autowired
    private ClueService clueService;

    @Autowired
    private MdQueryClient mdQueryClient;

    @Autowired
    @Lazy
    private ClueSyncService clueSyncService;

    @Autowired
    private ClueInitialIntentionVehicleService clueInitialIntentionVehicleService;
    @Autowired
    private CrmService crmService;
    @Autowired
    private IamIncCenterClient iamIncCenterClient;
    @Autowired
    private TenantClient tenantClient;
    @Autowired
    private DealerCustomerFollowRecordService dealerCustomerFollowRecordService;

    @Autowired
    private ClueLogService clueLogService;

    //crm的tenant
    @Value("${properties.default.tenant-id}")
    private String tenandId;
    //crm的corp
    @Value("${properties.default.corp-id}")
    private String corpId;
    //小程序等下发默认车系
    @Value("${access.add.defaultSeriesCode}")
    private String defaultSeriesCode;

    @Value("${access.add.defaultReceiveAfterWash}")
    private String defaultReceiveAfterWash;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private CommRedisDao commRedisDao;

    //同步老数据成功后：将crmClueId放入redis 由此键值触发record记录同步
    private String syncLeadTriggerRecord="LEAD:TRI:REC";

    //注册渠道 ---线索中心
    private static final String REGISTER_CHANNEL = "scrm-befsale-clue-service";

    //创建一个定长线程池，超出的线程会在队列中等待
    private ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);

    /**
     * 通过ID获取详细信息
     *
     * @param: request
     * @return: ClueInitial对象
     */
    @Override
    public ClueInitial getDetailById(Integer id) {
        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(id, "请求参数不能为空");
        ValidateUtils.checkIntNotNullAndGTZero(id, "ID不能为空或小于0");
        /** 2 处理业务 */
        ClueInitial clueInitial = clueInitialManager.getDetailById(id);
        if (EmptyUtils.isNotEmpty(clueInitial)) {
            return BeanUtil.copy(clueInitial, ClueInitial.class);
        }
        /** 3 返回结果 */
        return null;
    }

    /**
     * 单条数据插入ClueInitial
     *
     * @param request
     * @return 插入的条数
     */
    @Override
    public Long insert(ClueInitial request) {
        log.info("企微创建线索，手机号={},name={},startTime={}",request.getPhone(),request.getName(),DateUtil.toDateString(new Date(), DateUtil.BEANTECHS_DATE_FORMAT_PASS_SSSSSSS));
        //获取oneId
        request.setOneId(getOneIdByPhone(request.getPhone()));
        //上报crm进行清洗
        request.setStatus(InitialStatusEnum.STATUS_NEW.getCode());
        //线索源--添加
        request.setSourceFirst(InitialSourceFirstEnum.SOURCE_FIRST_ONLINE.getCode());
        request.setDeleted(DeletedEnum.EXIST.getCode());
        request.setCleanType(InitialCleanTypeEnum.TYPE_CLEAN.getCode());
        request.setCreatedTime(new Date());
        request.setFollowEmpName(request.getCreatedName());
        clueInitialManager.insert(request);
        if(request.getId()==null){
            throw new BusinessException(ClueErrorEnum.CLUE_INITIAL_SAVE_ERROR);
        }

        Long initialClueId=request.getId();
        //线索源--意向品牌车系等信息添加
        createInitialClueIntentionVehicle(request,initialClueId);

        //调用crm接口清洗
        SyncCrmCreateClueRequest dataToCrm=this.changeDataToCrm(request);
        crmService.clueInitialDataToCrm(dataToCrm,request);
        //修改线索源，处理清洗结果
        clueInitialManager.updateCrmClueId(request);
        if(request.getStatus()==InitialStatusEnum.STATUS_CRM.getCode()|| StringUtil.isEmpty(request.getCrmClueId())){
            throw new BusinessException(ClueErrorEnum.CLUE_INITIAL_SAVE_CLEAN_ERROR);
        }


        //线索源下发--组合线索源下发需要的参数
        request.setStatus(ClueStatsEnum.FOLLOW_UP.getCode());
        ClueFollowUpRequest clueFollowUpRequest=createClueFollowUpRequest(request);

        //线索下发-参数验证
        ClueErrorEnum clueErrorEnum = clueService.checkClueFollowUp(clueFollowUpRequest);
        if (clueErrorEnum != null) {
            throw new BusinessException(clueErrorEnum);
        }

        //验证oneId对应的客户是否已经存在其它跟进人，若存在则不允许创建线索
        String resulStr = clueSyncService.checkOneId(clueFollowUpRequest.getFollowUpCustomer().getOneId(), request.getDealerId(),
                clueFollowUpRequest.getFollowUpCustomer().getFollowEmpId(),request.getTenantId(),request.getCorpId());
        if (!StringUtils.isEmpty(resulStr)) {
            throw new BusinessException("该客户已经存在其它跟进人，" + resulStr);
        }
        //线索源下发--企微新增线索源 默认直接进行线索下发,获取线索id

        Long  clueId=clueService.createClueWithfollowUp(clueFollowUpRequest, InitalSendTypeEnum.SEND_TYPE_QW.getCode());
        //线索源下发--线索下发获取线索id后异步执行后续信息(线索的意向信息,意向品牌列表，计划跟进,跟进记录，宽表)
        clueSyncService.createClueWithfollowUpSync(clueFollowUpRequest,InitalSendTypeEnum.SEND_TYPE_QW.getCode());
        log.info("企微创建线索，手机号={},name={},endTime={}",request.getPhone(),request.getName(),DateUtil.toDateString(new Date(), DateUtil.BEANTECHS_DATE_FORMAT_PASS_SSSSSSS));
        return clueId;
    }

    /**
     * add by zly
     * 2022-01-20
     * 接收清洗后的数据
     * @param request
     * @return
     */
    @Override
    public Integer receiveAfterWash(AddClueInitialAfterWashRequest request) {
        //查看配置，若配置关闭则返回
        if(StringUtils.isEmpty(defaultReceiveAfterWash)){
            return 0;
        }
        log.info("receiveAfterWash接口接收crm同步的线索，入参={}",JSON.toJSONString(request));
        //第一步：根据crmClueId查看线索源表是否有对应的数据，有则修改，没有则新增
        ClueInitial checkRequest=new ClueInitial();
        checkRequest.setCrmClueId(request.getCrmClueId());
        checkRequest.setDeleted(DeletedEnum.EXIST.getCode());
        ClueInitial clueInitial=this.getOneclueInitialByParam(checkRequest);
        log.info("receiveAfterWash接口接收crm同步的线索，查看库里是否存在对应的线索clueInitial={}",JSON.toJSONString(clueInitial));
        if(clueInitial!=null){
            return 0;
        }
        Long initialClueId=null;
        if(clueInitial!=null){
            initialClueId=clueInitial.getId();
            //存在则修改
            this.initClue(request,clueInitial);
            clueInitial.setUpdatedTime(new Date());
            clueInitial.setUpdatedName("crm");
            this.update(clueInitial);
        }else{
            //不存在则新增
            clueInitial=new ClueInitial();
            clueInitial.setCrmClueId(request.getCrmClueId());
            this.initClue(request,clueInitial);
            clueInitial.setCreatedTime(new Date());
            clueInitial.setCreatedName("crm");
            clueInitial.setDeleted(DeletedEnum.EXIST.getCode());
            clueInitialManager.insert(clueInitial);
            initialClueId=clueInitial.getId();
        }

        //线索源--意向品牌车系等信息添加
        clueSyncService.initClueIntentionVehicle(request,initialClueId,clueInitial.getTenantId(),clueInitial.getCorpId(),clueInitial.getDealerId(),clueInitial);

        //线索源下发--组合线索源下发需要的参数
        ClueFollowUpRequest clueFollowUpRequest=createClueFollowUpRequest(clueInitial);
        //根据线索下发清洗状态，初始化线索状态,他们只会下发 新建和待下发的同步过来所以，所以直接为跟进中
        /*Integer clueStatus= clueService.initClueStatus(request.getStatus());
        if(clueStatus!=null) {*/
            clueFollowUpRequest.getFollowUpClue().setStatus(ClueStatsEnum.FOLLOW_UP.getCode());
            clueFollowUpRequest.getFollowUpClue().setDealerFollowStatus(clueInitial.getFollowEmpId()==null||clueInitial.getFollowEmpId()==-1?
                DealerFollowStatusEnum.DISTRIBUTION_DEALER.getCode():DealerFollowStatusEnum.DISTRIBUTION_ADVISER.getCode());
       // }
        //初始化客户状态
        clueFollowUpRequest.getFollowUpCustomer().setStatus(CustomerStatusEnum.NORMAL.getCode());
        //创建线索
        Long  clueId=clueService.createClueWithfollowUp(clueFollowUpRequest,InitalSendTypeEnum.SEND_TYPE_CRM.getCode());

        //线索源下发--线索下发获取线索id后异步执行后续信息(线索的意向信息,意向品牌列表，计划跟进,跟进记录，宽表)
        clueSyncService.createClueWithfollowUpSync(clueFollowUpRequest,InitalSendTypeEnum.SEND_TYPE_CRM.getCode());
        return 0;
    }

    /**
     * 意向品牌等信息添加
     * @param request
     * @param initialClueId
     */
    private void createInitialClueIntentionVehicle(ClueInitial request, Long initialClueId) {
       try {
        List<AddClueIntentionVehicleRequest> addVehicleList=request.getAddVehicleList();
        if(CollectionUtils.isNotEmpty(addVehicleList)&& addVehicleList.size()>0) {
            for (int i=0;i< addVehicleList.size();i++ ) {
                if(addVehicleList.get(i) instanceof AddClueIntentionVehicleRequest) {
                    ClueIntentionVehicle iv= ClueIntentionVehicleAssembler.transformVOToPO(addVehicleList.get(i),ClueIntentionVehicle.class);
                    iv.setTenantId(request.getTenantId());
                    iv.setCorpId(request.getCorpId());
                    iv.setDealerId(request.getDealerId());
                    iv.setCreatedName(request.getCreatedName());
                    iv.setCreatedBy(request.getCreatedBy());
                    iv.setCreatedTime(request.getCreatedTime());
                    iv.setClueInitialId(initialClueId);
                    iv.setDeleted(DeleteEnum.INIT.getFlag());
                    iv.setStatus(StatusEnum.TEMP_STOR.getCode());
                    clueInitialIntentionVehicleService.insert(iv);
                }
            }
        }
       }catch (Exception e){
           e.printStackTrace();
       }
    }

    /**
     * 根据手机号去iam获取oneId
     * add by zly
     * 2022-02-09
     * @param phone
     * @return
     */
    public String getOneIdByPhone(String phone){
        String oneId="";
        try {
            CenterPhoneRequest centerPhoneRequest = new CenterPhoneRequest();
            centerPhoneRequest.setPhone(phone);
            centerPhoneRequest.setNation("86");
            CenterPhoneResponse oneIdRes = iamIncCenterClient.getOneIdByPhones(centerPhoneRequest, "1");
            log.info("从iam获取oneId,返回信息={}", JSON.toJSONString(oneIdRes));
            if (oneIdRes != null && (oneIdRes.getCode() == 0 || oneIdRes.getCode() == 12006)) {
              oneId=oneIdRes.getData();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return oneId;
    }


    /**
     *  线索源下发到下游表，组合公共request
     * @param request 线索源信息
     * @return
     */
    public ClueFollowUpRequest createClueFollowUpRequest(ClueInitial request) {
        //如果oneId为空，根据手机号去iam获取oneId
        if(StringUtils.isEmpty(request.getOneId())){
            request.setOneId(getOneIdByPhone(request.getPhone()));
        }
        //获取线索源Id
        Long initialId=request.getId();
        //将线索源赋值为空，后面其它对象信息转换时则不会将线索源id赋值给对应的id
        request.setId(null);
        //客户跟进人处理，如果线索源本身没有客户跟进人，则赋值当前登录人的信息
        /*if (EmptyUtils.isEmpty(request.getFollowEmpId())) {
            if(EmptyUtils.isNotEmpty(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_EMP_ID.getCode()))){
                request.setFollowEmpId(Long.valueOf(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_EMP_ID.getCode())));
                request.setFollowEmpName(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_EMP_NAME.getCode()));
            }
        }else{
            //当跟进人不为空的时候，去org查询对应的人是否存在，存在则取对应的name,
            // 但是目前先将name赋值当前登录人（因为线索源创建后会里面下发线索，所以取当前登录人名称也不会事empId对应的empName错乱）
            if(EmptyUtils.isNotEmpty(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_EMP_ID.getCode()))){
                request.setFollowEmpName(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_EMP_NAME.getCode()));
            }
        }*/

        ClueFollowUpRequest clueFollowUpRequest=new ClueFollowUpRequest();
        //转换线索信息
        AddClueRequest followUpClue= ClueAssembler.transformVOToPO(request,AddClueRequest.class);
        followUpClue.setClueInitialId(initialId);
        if(!StringUtils.isEmpty(request.getFollowEmpId())&&!"-1".equals(request.getFollowEmpId())&&followUpClue.getDistributeTime()==null) {
            followUpClue.setDistributeTime(request.getCreatedTime());
        }
        clueFollowUpRequest.setFollowUpClue(followUpClue);

        //转换客户信息
        AddOemCustomerRequest followUpCustomer= OemCustomerAssembler.transformVOToPO(request,AddOemCustomerRequest.class);
        //填充customer_base_id
        if(StringUtil.isNotEmpty(followUpCustomer.getExternalUserid())){
            QueryCustomerBaseRequest baseRequest = new QueryCustomerBaseRequest();
            baseRequest.setDeleted(DeletedEnum.EXIST.getCode());
            baseRequest.setExternalUserid(followUpCustomer.getExternalUserid());
            log.info("调用主数据查询客户信息，外部联系人参数：【{}】",JSON.toJSONString(baseRequest));
            Response<List<CustomerBaseResponse>> response = mdQueryClient.getListByParam(baseRequest);
            log.info("调用主数据拆线呢客户信息，返回：【{}】",JSON.toJSONString(response));
            if(Objects.nonNull(response) && response.getCode() == 0 && CollectionUtils.isNotEmpty(response.getData())){
                Long id = response.getData().get(0).getId();
                followUpCustomer.setCustomerBaseId(id);
            }
        }
        clueFollowUpRequest.setFollowUpCustomer(followUpCustomer);
        //转换客户信息-客户扩展信息
        AddCustomerExtRequest followUpCustomerExt= CustomerExtAssembler.transformVOToPO(request,AddCustomerExtRequest.class);
        clueFollowUpRequest.setFollowUpCustomerExt(followUpCustomerExt);
        //转换客户信息--客户来源
        CustomerSourceInfo customerSourceInfo=CustomerExtAssembler.transformVOToPO(request,CustomerSourceInfo.class);
        clueFollowUpRequest.setCustomerSourceInfo(customerSourceInfo);

        //转换线索计划跟进信息
        AddOemCustomerFollowPlanRequest followUpPlan= OemCustomerFollowPlanAssembler.transformVOToPO(request,AddOemCustomerFollowPlanRequest.class);
        clueFollowUpRequest.setFollowUpPlan(followUpPlan);

        //转换线索跟进信息
        AddOemCustomerFollowRecordRequest followUpRecord= OemCustomerFollowRecordAssembler.transformVOToPO(request,AddOemCustomerFollowRecordRequest.class);
        clueFollowUpRequest.setFollowUpRecord(followUpRecord);

        //转换线索意向信息
        AddClueIntentionRequest followUpClueIntention= ClueIntentionAssembler.transformVOToPO(request,AddClueIntentionRequest.class);
        clueFollowUpRequest.setFollowUpClueIntention(followUpClueIntention);
        //转换线索意向信息--线索意向品牌，车系等集合信息
        clueFollowUpRequest.setAddVehicleList(request.getAddVehicleList());

        //基本标签，意向标签code-name对应的json信息
        clueFollowUpRequest.setCodeNameInfo(request.getCodeNameInfo());
        //获取线索源的经销商dealerId信息，线索下发时根据线索源的dealerId进行判断
        clueFollowUpRequest.setDealerId(request.getDealerId());
        return clueFollowUpRequest;
    }


    /**
     * 先根据手机号获取oneid
     * @param request
     * @return
     */
    public Long getOneId(ClueInitial request){
        if(StringUtil.isBlank(request.getPhone())){
            throw new BusinessException(ClueErrorEnum.CLUE_FIND_ONEID_BY_PHONE_ERROR);
        }
        //根据手机号等信息去主数据获取对应的oneId
        QueryUserRequest qur = new QueryUserRequest();
        qur.setName(request.getName());
        qur.setRegisterChannel(REGISTER_CHANNEL);
        qur.setPhone(request.getPhone());
        qur.setCorpId(request.getCorpId());
        qur.setTenantId(request.getTenantId());
        qur.setRegisterTime(request.getCreatedTime());
        qur.setEmpId(request.getFollowEmpId().toString());
        Response<CustomerBaseResponse> response =  mdQueryClient.getCustomerBaseByPhone(qur);
        if(response==null||response.getData()==null){
            throw new BusinessException(ClueErrorEnum.CLUE_FIND_ONEID_RESPONSE_ERROR);
        }
        CustomerBaseResponse customerBaseResponse = response.getData();
        return customerBaseResponse.getOneId();
    }







    /**
     * 批量插入ClueInitial
     *
     * @param requests
     * @return 批量插入的条数
     */
    @Override
    public int insertBatch(List<ClueInitial> requests) {
        /** 1 验证请求参数 */
        /** 2 处理业务 */
        int count = clueInitialManager.insertBatch(requests);
        /** 3 封装返回值 */
        return count;
    }


    /**
     * 单条ClueInitial更新
     *
     * @param request
     * @return 更新的条数
     */
    @Override
    public int update(ClueInitial request) {

        /** 1 验证请求参数 */
        /** 2 处理业务 */
        int count = clueInitialManager.update(request);
        /** 3 返回对象 */
        return count;
    }

    /**
     * 通过ID删除数据
     *
     * @param request
     * @return 删除的条数
     */
    @Override
    public int delete(ClueInitial request) {
        Long id = request.getId();
        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(id, "请求参数不能为空");
        ValidateUtils.checkLongNotNullAndGTZero(id, "ID不能为空或小于0");
        /** 2 处理业务 */
        ClueInitial clueInitial = new ClueInitial();
        clueInitial.setId(id);
//		clueInitial.setDelete(DeleteEnum.DETELED.getCode());
        int count = clueInitialManager.update(clueInitial);
        /** 3 返回对象 */
        return count;
    }

    /**
     * 根据条件查询对象对象list列表
     *
     * @param request
     * @return 查询结果
     */
    @Override
    public List<ClueInitial> getListByParam(ClueInitial request) {
        /** 1 验证请求参数 */
        //可以设置排序
        /** 2 处理业务 */
        List<ClueInitial> queryList = clueInitialManager.getListByParam(request);
        /** 3 返回结果 */
        if (CollectionUtils.isNotEmpty(queryList)) {
            return BeanUtil.copyByList(queryList, ClueInitial.class);
        }
        return new ArrayList<>();
    }

    /**
     * 根据条件查询对象-单个
     *add by zly
     * 2022-01-20
     * @param request
     * @return 查询结果
     */
    @Override
    public ClueInitial getOneclueInitialByParam(ClueInitial request) {
        ClueInitial oneClueInit = clueInitialManager.getOneclueInitialByParam(request);
        return oneClueInit;
    }

    /**
     * 根据条件查询对象list记录
     *
     * @param request
     * @return 分页对象
     */
    @Override
    public PageResponse<ClueInitial> getPageByParam(PageRequest<ClueInitial> request) {
        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(request, "请求参数不能为空");
        //可以设置排序 query.orderByCreatedTime(true);
        /** 2 处理业务 */
        RowBounds rowBounds = new RowBounds(request.getPageNum(), request.getPageSize());
        Page<ClueInitial> queryPageList = clueInitialManager.getPageByParam(request.getParamData(), rowBounds);
        PageResponse<ClueInitial> pageResponse = new PageResponse<>();
        pageResponse.converPageResponse(pageResponse, queryPageList, request);
        pageResponse.setDataList(BeanUtil.copyByList(queryPageList.getResult(), ClueInitial.class));
        /** 3 返回结果 */
        return pageResponse;
    }

    @Override
    public int washHandle() {
        return 0;
    }



    /**
     * 处理清洗下来的线索基本信息
     * @param request
     * @param clueInitial
     */
    private void initClue(AddClueInitialAfterWashRequest request, ClueInitial clueInitial){
        //crm清洗下来的数据，线索源的状态统一改成已处理
        clueInitial.setStatus(InitialStatusEnum.STATUS_DEAL_WITH.getCode());
        clueInitial.setCleanType(InitialCleanTypeEnum.TYPE_DEAL_WITH.getCode());

        clueInitial.setSourceFirst(request.getSourceFirst());
        if(request.getSourceSecond()==null) {
           if(clueInitial.getSourceSecond()==null){
               clueInitial.setSourceSecond(InitialSourceSecondEnum.SOURCE_SECOND_DEALER.getCode());
           }
        }else{
            clueInitial.setSourceSecond(request.getSourceSecond());
        }

        clueInitial.setSourceActivityId(request.getSourceActivityId());
        clueInitial.setPhone(request.getPhone());
        clueInitial.setName(request.getName());
        clueInitial.setGender(request.getGender());
        clueInitial.setBirthday(request.getBirthday());
        clueInitial.setAddress(request.getAddress());
        clueInitial.setCusRemark(request.getCusRemark());
        clueInitial.setDistributeDealerCode(request.getDistributeDealerCode());
        clueInitial.setDistributeEmp(request.getDistributeEmp());
        clueInitial.setTenantId(tenandId);
        clueInitial.setCorpId(corpId);
        //三级渠道转化
        if(StringUtil.isNotEmpty(request.getSourceThird())) {
            QueryDictionariesRequest requestThird=new QueryDictionariesRequest();
            requestThird.setName(request.getSourceThird());
            requestThird.setType("bef_sale_customer_source_third");//联调成功后配置到nacos
            Response<List<DictionariesResponse>> sourceThirdRes = tenantClient.getDictionariesListByParam(requestThird);
            if(sourceThirdRes!=null&&sourceThirdRes.getData()!=null&&sourceThirdRes.getData().size()>0){
                DictionariesResponse thirdOne=sourceThirdRes.getData().get(0);
                clueInitial.setSourceThird(thirdOne.getCode());
            }
        }
        clueInitial.setOneId(getOneIdByPhone(request.getPhone()));
        // provinceName省名称  ,cityName市名称 districtName区域名称转对应的code
        this.getProvinceWithArea(request.getProvinceName(),request.getCityName(),request.getDistrictName(),clueInitial);
        //顾问的userid，转化empId
        this.getChangeEmp(request.getDistributeEmp(), clueInitial);

        //经销商code转化经销商id
        if(StringUtil.isNotEmpty(request.getDistributeDealerCode())) {
            DealerResponse dealer= this.getChangeDealer(request.getDistributeDealerCode(), tenandId,corpId);
           if(dealer!=null) {
               clueInitial.setDealerId(dealer.getId().toString());
               if (StringUtils.isEmpty(clueInitial.getProvinceCode())) {
                   clueInitial.setProvinceCode(dealer.getProvinceCode());
               }
               if (StringUtils.isEmpty(clueInitial.getCityCode())) {
                   clueInitial.setCityCode(dealer.getCityCode());
               }
               if (StringUtils.isEmpty(clueInitial.getDistrictCode())) {
                   clueInitial.setDistrictCode(dealer.getDistrictCode());
               }
           }
        }

    }

    /**
     * 经销商code转化经销商id
     * @param dealerCode
     * @param tenandId
     * @param corpId
     */
    private DealerResponse getChangeDealer(String dealerCode,String tenandId,String corpId) {
        try {
            QueryDealerRequest dealerRequest = new QueryDealerRequest();
            dealerRequest.setCode(dealerCode);
            dealerRequest.setTenantId(tenandId);
            dealerRequest.setCorpId(corpId);
            log.info("接收线索清洗数据，根据经销商code拿经销商id,请求参数ddealerRequest={},tenantId={},corp={}",dealerRequest,tenandId, corpId);
            Response<DealerResponse> dealerRes = mdQueryClient.getOneDealerByParam(dealerRequest, tenandId, corpId);
            log.info("接收线索清洗数据，根据经销商code拿经销商id,返回信息dealerRes={}", JSON.toJSONString(dealerRes));
            if (dealerRes != null && dealerRes.getData() != null) {
                DealerResponse dealer = dealerRes.getData();
                return dealer;
            }
        }catch (Exception e){
            log.error("接收线索清洗数据，根据经销商code拿经销商id,方法异常，error={}",e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 经销商code转化经销商id
     * @param tenandId
     * @param corpId
     */
    private void getChangeDealerById(Long dealerId,String tenandId,String corpId,SyncCrmCreateClueRequest dataToCrm,ClueInitial c) {
        try {
            QueryDealerRequest dealerRequest = new QueryDealerRequest();
            dealerRequest.setId(dealerId);
            dealerRequest.setTenantId(tenandId);
            dealerRequest.setCorpId(corpId);
            log.info("上报线索源到crm，根据经销商id拿经销商code,请求参数ddealerRequest={},tenantId={},corp={}",dealerRequest,tenandId, corpId);
            Response<DealerResponse> dealerRes = mdQueryClient.getOneDealerByParam(dealerRequest, tenandId, corpId);
            log.info("上报线索源到crm，根据经销商id拿经销商code,返回信息dealerRes={}", JSON.toJSONString(dealerRes));
            if (dealerRes != null && dealerRes.getData() != null) {
                DealerResponse dealer = dealerRes.getData();
                dataToCrm.setDealers(dealer.getCode().toString());
                if(StringUtils.isEmpty(c.getProvinceCode())){
                    c.setProvinceCode(dealer.getProvinceCode());
                }
                if(StringUtils.isEmpty(c.getCityCode())){
                    c.setCityCode(dealer.getCityCode());
                }
                if(StringUtils.isEmpty(c.getDistrictCode())){
                    c.setDistrictCode(dealer.getDistrictCode());
                }
            }
        }catch (Exception e){
            log.error("上报线索源到crm，根据经销商id拿经销商code,方法异常，error={}",e.getMessage());
            e.printStackTrace();
        }
    }





    /**
     * provinceName省名称  ,cityName市名称 districtName区域名称转对应的code
     * @param
     * @param clueInitial
     */
    private void getProvinceWithArea(String provinceName,String cityName,String districtName, ClueInitial clueInitial) {
        try {
            QueryAreaRequest areaRequest = new QueryAreaRequest();
            //根据省份名称查省份code
            if (StringUtil.isNotEmpty(provinceName)) {
                areaRequest.setName(provinceName);
                log.info("接收线索清洗数据，根据省份名称拿对应的code,请求参数provinceName={},tenantId={},corp={}",provinceName,clueInitial.getTenantId(), clueInitial.getCorpId());
                Response<AreaResponse> areaProvince = mdQueryClient.getOneAreaByParam(areaRequest, clueInitial.getTenantId(), clueInitial.getCorpId());
                log.info("接收线索清洗数据，根据省份名称拿对应的code,返回信息areaProvince={}", JSON.toJSONString(areaProvince));
                if (areaProvince != null && areaProvince.getData() != null) {
                    AreaResponse province = areaProvince.getData();
                    clueInitial.setProvinceCode(province.getCode());
                }
            }
            //根据城市名称查城市code
            if (StringUtil.isNotEmpty(cityName)) {
                areaRequest.setName(cityName);
                log.info("接收线索清洗数据，根据根据城市名称查城市code,请求参数cityName={},tenantId={},corp={}",cityName,clueInitial.getTenantId(), clueInitial.getCorpId());
                Response<AreaResponse> areaCity = mdQueryClient.getOneAreaByParam(areaRequest, clueInitial.getTenantId(), clueInitial.getCorpId());
                log.info("接收线索清洗数据，根据根据城市名称查城市code,返回信息areaCity={}", JSON.toJSONString(areaCity));
                if (areaCity != null && areaCity.getData() != null) {
                    AreaResponse city = areaCity.getData();
                    clueInitial.setCityCode(city.getCode());
                }
            }

            //根据区名称拿对应的code
            if (StringUtil.isNotEmpty(districtName)) {
                areaRequest.setName(districtName);
                log.info("接收线索清洗数据，根据根据区名称拿对应的code,请求参数districtName={},tenantId={},corp={}",districtName,clueInitial.getTenantId(), clueInitial.getCorpId());
                Response<AreaResponse> areaDistrict = mdQueryClient.getOneAreaByParam(areaRequest, clueInitial.getTenantId(), clueInitial.getCorpId());
                log.info("接收线索清洗数据，根据根据区名称拿对应的code,返回信息areaProvince={}", JSON.toJSONString(areaDistrict));
                if (areaDistrict != null && areaDistrict.getData() != null) {
                    AreaResponse district = areaDistrict.getData();
                    clueInitial.setDistrictCode(district.getCode());
                }
            }
        }catch (Exception e){
            log.error("接收线索清洗数据，根据省市区name获取对应的code方法异常，error={}",e.getMessage());
            e.printStackTrace();
        }
    }

    private AreaResponse getProvinceWithAreaBycode(QueryAreaRequest areaRequest) {
        try {
            if(!StringUtils.isEmpty(areaRequest.getCode())) {
                log.info("根据条件获取对应的省市区信息,参数areaRequest={}", JSON.toJSONString(areaRequest));
                Response<AreaResponse> area = mdQueryClient.getOneAreaByParam(areaRequest, areaRequest.getTenantId(), areaRequest.getCorpId());
                log.info("根据条件获取对应的省市区信息,返回信息area={}", JSON.toJSONString(area));
                if (area != null && area.getData() != null) {
                    AreaResponse areaResponse = area.getData();
                    return areaResponse;
                }
            }else{
                return null;
            }
        }catch (Exception e){
            log.error("接收线索清洗数据，根据省市区name获取对应的code方法异常，error={}",e.getMessage());
            e.printStackTrace();
        }
        return null;
    }



    /**
     * 顾问的userid，转化empId
     * @param empUserId
     * @param clueInitial
     */
    private void getChangeEmp(String empUserId, ClueInitial clueInitial){
        try {
            if (StringUtil.isEmpty(empUserId)) {
                return;
            }
            log.info("接收线索清洗数据，根据顾问userId获取顾问id,请求参数empUserId={},tenantId={},corpId={}",empUserId,clueInitial.getTenantId(),clueInitial.getCorpId());
            Response<EmployeeResponse> empRes = mdQueryClient.byEmpByUserid(empUserId, clueInitial.getTenantId(), clueInitial.getCorpId());
            log.info("接收线索清洗数据，根据顾问userId获取顾问id,返回信息empRes={}", JSON.toJSONString(empRes));
            if (empRes != null && empRes.getData() != null) {
                EmployeeResponse emp = empRes.getData();
                clueInitial.setFollowEmpId(emp.getId());
                clueInitial.setFollowEmpName(emp.getName());
            }
        }catch (Exception e){
            log.error("接收线索清洗数据，根据顾问userId获取顾问id,方法异常，error={}",e.getMessage());
            e.printStackTrace();
        }

    }


    /**
     * 同步线索源信息到crm
     * add by zly 2022-01-22
     * @param sysnTime
     * @return
     */
    @Override
    public Boolean syncClueInitialToCrm(String sysnTime) {
        //获取需要同步的数据
        ClueInitial request=new ClueInitial();
        request.setDeleted(DeletedEnum.EXIST.getCode());
        request.setStatus(InitialStatusEnum.STATUS_NEW.getCode());
        request.setCrmClueId(null);
        Integer count=clueInitialManager.getSyncToCrmCountByParam(request);
        if(count>0) {
            Integer pageSize = 5;
            request.setPageSize(pageSize);
            Integer pageTotal = (count % pageSize) > 0 ? (count / pageSize) + 1 : count / pageSize;
            for (int i = 0; i < pageTotal; i++) {
                Integer pageStart = i * pageSize;
                fixedThreadPool.execute(new Runnable() {
                    public void run() {
                        syncClueInitialToCrmPage(request, pageStart);
                    }
                });
            }
        }
        return null;
    }


    private void syncClueInitialToCrmPage(ClueInitial request, Integer pageStart) {
        ClueInitial requestPage= ClueDayStatsAssembler.transformPOToResponseVo(request,ClueInitial.class);
        requestPage.setPageIndex(pageStart);
        log.info("数据源定时同步给crm-分页查看库里需要同步的数据requestPage={},pageStart={}",JSON.toJSONString(requestPage),pageStart);
        List<ClueInitial> listPage= clueInitialManager.getSyncToCrmPageByParam(requestPage);
        log.info("数据源定时同步给crm-分页查看库里需要同步的数据listPage={}",JSON.toJSONString(listPage));
        if(CollectionUtils.isEmpty(listPage)){
            return;
        }
        //循环要同步的数据
        listPage.stream().forEach(c->{
            if(!StringUtils.isEmpty(c.getDealerId())&&!"0".equals(c.getDealerId())) {
                //调用crm清洗线索
                SyncCrmCreateClueRequest dataToCrm = this.changeDataToCrm(c);
                crmService.clueInitialDataToCrm(dataToCrm, c);
                clueInitialManager.updateCrmClueId(c);
                //如果线索返回已处理，直接同步线索源到线索池
                if(InitialStatusEnum.STATUS_DEAL_WITH.getCode()==c.getStatus()&&!StringUtil.isEmpty(c.getCrmClueId())){
                    //线索源下发--组合线索源下发需要的参数
                    ClueFollowUpRequest clueFollowUpRequest=createClueFollowUpRequest(c);
                     if(!StringUtils.isEmpty(clueFollowUpRequest.getFollowUpCustomer().getOneId())) {

                         //验证客户是否存在活跃线索，若存在，则不允许创建
                         ClueErrorEnum clueErrorEnum = clueService.checkClueFollowUp(clueFollowUpRequest);

                         //验证oneId对应的客户是否已经存在其它跟进人或者同一个经销商是否存在相同的客户，若存在则不允许创建线索
                         String resulStr = clueSyncService.checkOneId(clueFollowUpRequest.getFollowUpCustomer().getOneId(), request.getDealerId(),
                                 clueFollowUpRequest.getFollowUpCustomer().getFollowEmpId(), request.getTenantId(), request.getCorpId());

                         if (StringUtils.isEmpty(resulStr)&&clueErrorEnum==null) {
                             Set<String> codeNameInfo = new HashSet<>();
                             //初始化codeNameInfo
                             //根据渠道code拿对应的渠道名称
                             QueryDictionariesRequest hRequest = new QueryDictionariesRequest();
                             hRequest.setType("bef_sale_customer_source_third");
                             hRequest.setCode(c.getSourceThird());
                             Response<List<DictionariesResponse>> hDicResponse = tenantClient.getDictionariesListByParam(hRequest);
                             log.info("数据源定时同步给crm-根据渠道查名称 入参={}，结果={}",JSON.toJSONString(hRequest),JSON.toJSONString(hDicResponse));
                             if (hDicResponse != null && hDicResponse.getData() != null && hDicResponse.getData().size() > 0) {
                                 DictionariesResponse hDicRes = hDicResponse.getData().get(0);
                                 codeNameInfo.add(hDicRes == null ? "" : hDicRes.getName());//渠道名称
                             }
                             // codeNameInfo.add(clueInitial.getSourceThird());//渠道名称
                             //根据活动code拿对应的活动名称 bef_sale_customer_source_activity_id
                             QueryDictionariesRequest aRequest = new QueryDictionariesRequest();
                             aRequest.setType("bef_sale_customer_source_activity_id");
                             aRequest.setCode(c.getSourceActivityId());
                             Response<List<DictionariesResponse>> dicResponse = tenantClient.getDictionariesListByParam(aRequest);
                             log.info("数据源定时同步给crm-根据活动code查名称 入参={}，结果={}",JSON.toJSONString(aRequest),JSON.toJSONString(dicResponse));
                             if (dicResponse != null && dicResponse.getData() != null && dicResponse.getData().size() > 0) {
                                 DictionariesResponse dicRes = dicResponse.getData().get(0);
                                 codeNameInfo.add(dicRes == null ? "" : dicRes.getName());//活动名称
                             }
                             codeNameInfo.add(c.getEducation());
                             codeNameInfo.add(c.getMarriage());
                             codeNameInfo.add(c.getFamilyNum());
                             codeNameInfo.remove(null);
                             codeNameInfo.remove("");
                             clueFollowUpRequest.setCodeNameInfo(JSON.toJSONString(codeNameInfo));
                             //根据线索下发清洗状态，初始化线索状态
                             clueFollowUpRequest.getFollowUpClue().setStatus(ClueStatsEnum.FOLLOW_UP.getCode());
                             //初始化客户状态
                             clueFollowUpRequest.getFollowUpCustomer().setStatus(CustomerStatusEnum.NORMAL.getCode());
                             //创建线索
                             Long clueId = clueService.createClueWithfollowUp(clueFollowUpRequest, InitalSendTypeEnum.SEND_TYPE_CRM.getCode());

                             //线索源下发--线索下发获取线索id后异步执行后续信息(线索的意向信息,意向品牌列表，计划跟进,跟进记录，宽表)
                             clueSyncService.createClueWithfollowUpSync(clueFollowUpRequest, InitalSendTypeEnum.SEND_TYPE_CRM.getCode());
                         }else{
                             if(clueErrorEnum!=null){
                                 log.info("定时器同步线索源到crm成功，但是客户【{}】在线索池已经存在活跃线索,所以此线索源数据不同步到线索池",c.getPhone());
                             }
                             if(StringUtils.isEmpty(resulStr)) {
                                 log.info("定时器同步线索源到crm成功，但是客户【{}】在线索池已经存在其它跟进人：{},所以此线索源数据不同步到线索池", c.getPhone(), resulStr);
                             }
                             AddCustomerFollowRecordRequest recordRequest= OemCustomerFollowRecordAssembler.transformVOToPO(request,AddCustomerFollowRecordRequest.class);
                             recordRequest.setId(null);
                             recordRequest.setStatus(FollowRecordStatusEnum.INIT.getCode());
                             recordRequest.setSecondStatus(FollowRecordSecondStatusEnum.INIT_INVALID.getCode());
                             recordRequest.setCusId(-1l);
                             recordRequest.setClueId(c.getId());
                             recordRequest.setSyncRemark("定时器同步线索至crm,线索没有入库线索源原因,clueErrorEnum="+JSON.toJSONString(clueErrorEnum)+"; 是否存在其它跟进人resulStr="+resulStr);
                             dealerCustomerFollowRecordService.insert(recordRequest);
                         }
                     }
                }
            }
        });
        //线索源批量同步返回的crmClueId入库
        //clueInitialManager.updateBatch(listPage);
    }

    private String getSiteCode(ClueInitial c){
       String siteCode= clueInitialManager.getSiteCode(c);
       return siteCode;
    }

    private SyncCrmCreateClueRequest changeDataToCrm(ClueInitial c) {
        log.info("企微创建线索，手机号={},name={},转换crm接口需要的入参开始时间startTime={}",c.getPhone(),c.getName(),DateUtil.toDateString(new Date(), DateUtil.BEANTECHS_DATE_FORMAT_PASS_SSSSSSS));
        String carSeries="";//车系名称
        String seriesCode="";//车系code
        String modelYearName="";//年款名称
        String modelYearCode="";//年款code
        String configName="";//配置名称
        String configCode="";//配置code
        if(CollectionUtils.isNotEmpty(c.getAddVehicleList())){
            AddClueIntentionVehicleRequest veh=c.getAddVehicleList().get(0);
            if(veh!=null) {
                carSeries = veh.getSeriesName();
                if(!StringUtils.isEmpty(veh.getSeriesId())) {
                    QueryVehicleSeriesRequest seriesRequest = new QueryVehicleSeriesRequest();
                    seriesRequest.setId(Long.valueOf(veh.getSeriesId()));
                    Response<VehicleSeriesResponse> seriesRes = mdQueryClient.getOneSeriesByParam(seriesRequest);
                    if (seriesRes != null && seriesRes.getData() != null) {
                        VehicleSeriesResponse serRes = seriesRes.getData();
                        seriesCode=serRes.getCode();
                    }
                }
                //根据 车型拿 年款和配置
                if(!StringUtils.isEmpty(veh.getModelId())) {
                    QueryVehicleModelRequest modelRequest = new QueryVehicleModelRequest();
                    modelRequest.setId(Long.valueOf(veh.getModelId()));
                    Response<VehicleModelResponse> modelRes = mdQueryClient.getOneModelByParam(modelRequest);
                    if (modelRes != null && modelRes.getData() != null) {
                        VehicleModelResponse model=modelRes.getData();
                         modelYearName=model.getAnnualModelName();//年款名称
                         modelYearCode=model.getYearCode();//年款code
                         configName=model.getConfigName();//配置名称
                         configCode=model.getConfigCode();//配置code
                    }
                }
            }
        }
        String siteCode="";//"905f5965-b22b-495c-b99a-02ca799aae96";
        if(!StringUtils.isEmpty(c.getSourceThird())&&!StringUtils.isEmpty(c.getSourceActivityId())){
            siteCode=getSiteCode(c);
        }

        //预约时间
        String driverDate=null;
        if(c.getPlanFollowTime()!=null) {
            driverDate= DateUtil.toDateString(c.getPlanFollowTime(), DateUtil.DEFAULT_DATETIME_PATTERN);
        }
        String salePhone="";
        if(c.getFollowEmpId()!=null&&c.getFollowEmpId()!=-1){
            //查看跟进人的手机号
            Response<EmployeeResponse> empRes=  mdQueryClient.getByIdWithOutRole(c.getFollowEmpId());
            if(empRes!=null&&empRes.getData()!=null) {
                EmployeeResponse emp=empRes.getData();
                salePhone=emp.getMobile();
            }
        }
        String genderStr="保密";
        if(c.getGender()!=null){
            if(c.getGender()==GenderEnum.GENDER_MALE.getCode()){
                genderStr="男";
            }else if(c.getGender()==GenderEnum.GENDER_FEMALE.getCode()){
                genderStr="女";
            }
        }
        SyncCrmCreateClueRequest dataToCrm=SyncCrmCreateClueRequest.builder()
                .carSeries(carSeries)// y
               // .province(provinceName)//y
                //.city(cityName)//y
                //.district(districtName)
                .detailAddress(c.getAddress())//详细地址
               // .dealers()//y
                .userName(c.getName())//y
                .mobile(c.getPhone())//y
                .gender(genderStr)
                .siteCode(siteCode)//y
                .channel(c.getSourceThird())
                .active(c.getSourceActivityId())
                .driverDate(driverDate)
                .leaveWords(c.getCusRemark())
                .sourceCompany("scrm")// y 定值
                .saleName(c.getFollowEmpName())
                .salePhone(salePhone)
                .seriesCode(seriesCode)
                .seriesName(carSeries)
                .modelName(modelYearName)
                .modelCode(modelYearCode)
                .rangeName(configName)
                .rangeCode(configCode)
                .build();
        //根据经销商id获取经销商code,若线索省市区为空，则也拿省市区
        this.getChangeDealerById(Long.valueOf(c.getDealerId()),c.getTenantId(),c.getCorpId(),dataToCrm,c);
        //省市区转化
        QueryAreaRequest areaRequest=new QueryAreaRequest();
        areaRequest.setTenantId(c.getTenantId());
        areaRequest.setCorpId(c.getCorpId());
        areaRequest.setCode(c.getProvinceCode());
        AreaResponse provinceArea=getProvinceWithAreaBycode(areaRequest);
        if(provinceArea!=null){
            dataToCrm.setProvince(provinceArea.getName());
        }
        areaRequest.setCode(c.getCityCode());
        AreaResponse cityArea=getProvinceWithAreaBycode(areaRequest);
        if(cityArea!=null){
            dataToCrm.setCity(cityArea.getName());
        }
        areaRequest.setCode(c.getDistrictCode());
        AreaResponse districtArea=getProvinceWithAreaBycode(areaRequest);
        if(districtArea!=null){
            dataToCrm.setDistrict(districtArea.getName());
        }
        log.info("企微创建线索，手机号={},name={},转换crm接口需要的入参结束时间endTime={}",c.getPhone(),c.getName(),DateUtil.toDateString(new Date(), DateUtil.BEANTECHS_DATE_FORMAT_PASS_SSSSSSS));
        return dataToCrm;
    }




    /**
     * 单条数据插入ClueInitial
     * add by zly
     * 2022-01-22
     * 接收从第三方创建的线索-入库线索源
     * @param accessRequest
     * @return 插入的条数
     */
    @Override
    public ThirdCreateClueInitialResponse accessAdd(AccessAddClueInitialRequest accessRequest) {
        //方法验证
        ClueErrorEnum accessAddCheckEnum=this.accessAddCheck(accessRequest);
        if (accessAddCheckEnum != null) {
            throw new BusinessException(accessAddCheckEnum);
        }
        ClueInitial request= ClueInitialAssembler.transformVOToPO(accessRequest, ClueInitial.class);
        //重新获取oneid
        String phone = request.getPhone();
        request.setOneId(getOneIdByPhone(phone));

        //线索源--添加
        request.setStatus(InitialStatusEnum.STATUS_NEW.getCode());
        request.setDeleted(DeletedEnum.EXIST.getCode());
        request.setCleanType(InitialCleanTypeEnum.TYPE_CLEAN.getCode());
        request.setCreatedBy("accessAdd");
        request.setCreatedTime(new Date());
        request.setDistributeDealerCode(accessRequest.getDealerCode());
        if(accessRequest.getGender()==null){
            request.setGender(GenderEnum.GENDER_UNKNOWN.getCode());
        }
        //将dealerCode转化为经销商id,erpId是什么？？
        DealerResponse dealer= this.getChangeDealer(accessRequest.getDealerCode(), tenandId,corpId);
        if(dealer!=null) {
            request.setDealerId(dealer.getId().toString());
            if(StringUtils.isEmpty(request.getProvinceCode())){
                request.setProvinceCode(dealer.getProvinceCode());
            }
            if(StringUtils.isEmpty(request.getCityCode())){
                request.setCityCode(dealer.getCityCode());
            }
            if(StringUtils.isEmpty(request.getDistrictCode())){
                request.setDistrictCode(dealer.getDistrictCode());
            }
        }
        request.setTenantId(tenandId);
        request.setCorpId(corpId);
        clueInitialManager.insert(request);
        Long initialClueId=request.getId();
        //线索源--意向品牌车系等信息添加--需将车系code,车型code转化为对应的id,和name
        List<AccessAddClueInitialRequest.VehicleSeriesAndModelRequest> intentionVehicleList=accessRequest.getIntentionVehicleList();
        if(CollectionUtils.isEmpty(intentionVehicleList)||intentionVehicleList.size()==0){
            AccessAddClueInitialRequest.VehicleSeriesAndModelRequest re=new AccessAddClueInitialRequest.VehicleSeriesAndModelRequest();
            re.setSeriesCode(defaultSeriesCode);
            intentionVehicleList=new ArrayList<>();
            intentionVehicleList.add(re);
            accessRequest.setIntentionVehicleList(intentionVehicleList);
        }else if(intentionVehicleList.size()==1&&StringUtils.isEmpty(intentionVehicleList.get(0).getSeriesCode())){
            intentionVehicleList.get(0).setSeriesCode(defaultSeriesCode);
        }
        clueSyncService.initClueIntentionVehicleByCode(intentionVehicleList,initialClueId,request.getTenantId(),request.getCorpId(),request.getDealerId());
        ThirdCreateClueInitialResponse result=new ThirdCreateClueInitialResponse();
        result.setInitialClueId(initialClueId);
        result.setIsSuccess(true);
        return result;
    }



    private ClueErrorEnum accessAddCheck(AccessAddClueInitialRequest accessRequest) {
        if (StringUtils.isEmpty(accessRequest.getRequestId())) {
            return ClueErrorEnum.CLUE_ACCESS_ADD001_ERROR;
        }
        if (StringUtils.isEmpty(accessRequest.getSourceFirst())) {
            return ClueErrorEnum.CLUE_ACCESS_ADD002_ERROR;
        }
        if (StringUtils.isEmpty(accessRequest.getSourceSecond())) {
            return ClueErrorEnum.CLUE_ACCESS_ADD003_ERROR;
        }
        if (StringUtils.isEmpty(accessRequest.getSourceThird())) {
            return ClueErrorEnum.CLUE_ACCESS_ADD004_ERROR;
        }
        if (StringUtils.isEmpty(accessRequest.getPhone())||accessRequest.getPhone().length()!=11) {
            return ClueErrorEnum.CLUE_ACCESS_ADD005_ERROR;
        }
        if (StringUtils.isEmpty(accessRequest.getSourceActivityId())) {
            return ClueErrorEnum.CLUE_ACCESS_ADD006_ERROR;
        }
        if (StringUtils.isEmpty(accessRequest.getDealerCode())) {
            return ClueErrorEnum.CLUE_ACCESS_ADD007_ERROR;
        }
        /*if (CollectionUtils.isEmpty(accessRequest.getIntentionVehicleList())) {
            return ClueErrorEnum.CLUE_ACCESS_ADD008_ERROR;
        }*/
        /*if (StringUtils.isEmpty(accessRequest.getAccessAddType())) {
            return ClueErrorEnum.CLUE_ACCESS_ADD009_ERROR;
        }*/
       /* if (StringUtils.isEmpty(accessRequest.getAccessAddNumber())) {
            return ClueErrorEnum.CLUE_ACCESS_ADD010_ERROR;
        }
        if (StringUtils.isEmpty(accessRequest.getAccessAddTime())) {
            return ClueErrorEnum.CLUE_ACCESS_ADD011_ERROR;
        }*/
        return null;
    }


    /**
     * 将CRM中线索状态为1-新建、2-已下发、3-已撞单、
     * 4-已失效 、5-已拒绝 、16-已回访 、17-自测 、
     * 20-申请失效 、21-待下发、13-已报价 状态迁移后全部转为 已战败状态
     * 同步crm老数据入库线索源
     * @param clueLead
     */
    @Override
    @Transactional(transactionManager = "qw_sale_mastertx", rollbackFor = Exception.class)
    public void sysnOldClueFromMq(ClueInitialCrm clueLead) {

            //如果手机号为空，或者包含*则视为垃圾数据，不接收
            if (clueLead.getPhone() == null || clueLead.getPhone().contains("*")) {
                log.error("手机号为空或者包含*，所以不入库线索源表");
                return;
            }

            //先查看线索源表里是否有对应的crmClueId对应的数据，若存在不入库线索源表
            ClueInitial checkRequest=new ClueInitial();
            checkRequest.setCrmClueId(clueLead.getCrmClueId());
            ClueInitial checkClueInitial=this.getOneclueInitialByParam(checkRequest);
            if(checkClueInitial!=null) {
                log.error("crmClueId="+clueLead.getCrmClueId()+"的数据已在线索源表存在，所以不重复入库线索源表");
                return;
            }

            //第一步 数据转化
            Set<String> codeNameInfo = new HashSet<>();
            ClueInitial clueInitial = ClueInitialAssembler.transformVOToPO(clueLead, ClueInitial.class);
            //获取oneId
            String oneId=getOneIdByPhone(clueInitial.getPhone());
            clueInitial.setOneId(StringUtils.isEmpty(oneId)?clueInitial.getPhone():oneId);
            //初始化线索源状态
            clueInitial.setStatus( InitialStatusEnum.STATUS_DEAL_WITH.getCode());
            //线索源
            clueInitial.setSourceFirst(InitialSourceFirstEnum.SOURCE_FIRST_ONLINE.getCode());

            clueInitial.setDeleted(DeletedEnum.EXIST.getCode());
            clueInitial.setCleanType(InitialCleanTypeEnum.TYPE_DEAL_WITH.getCode());
            clueInitial.setTenantId(tenandId);
            clueInitial.setCorpId(corpId);
            clueInitial.setCreatedTime(clueLead.getCreateTime());
            Integer crmLeadStatusChangeFail= clueService.initClueInitStatus(clueLead.getLeadStatus());
            if(crmLeadStatusChangeFail==null) {
                clueInitial.setCreatedName("sysnCrm");
                clueInitial.setCreatedBy("sysnCrm");
            }else{
                clueInitial.setCreatedName("sysnCrm"+crmLeadStatusChangeFail);
                clueInitial.setCreatedBy("sysnCrm"+crmLeadStatusChangeFail);
            }
            //渠道转化，活动转化
            clueInitial.setSourceThird(clueLead.getChannelCode());
            clueInitial.setSourceActivityId(clueLead.getActivityCode());
            //dictionary 表module=GENDER 字典（1男，2女，3未知）
            String genderCrm = clueLead.getGenderCrm();
            if (!StringUtils.isEmpty(genderCrm)) {
                if ("1".equals(genderCrm)) {
                    clueInitial.setGender(1);//gender:0表示未定义，1表示男性，2表示女性
                } else if ("2".equals(genderCrm)) {
                    clueInitial.setGender(2);
                } else {
                    clueInitial.setGender(0);
                }
            }

            //婚姻  dictionary 表module=IF_MARRIED 字典（1已婚，2未婚）
            String ifMarried = clueLead.getIfMarried();
            if (!StringUtils.isEmpty(ifMarried)) {
                clueInitial.setMarriage("1".equals(ifMarried) ? "已婚" : "未婚");
            }
            //家庭人数 dictionary 表module=FAMILY_SIZE 字典（1 1人,2 2人,3 3人,4 4人,5 5人及以上）
            String familySize = clueLead.getFamilySize();
            if (!StringUtils.isEmpty(familySize)) {
                Integer familySizeCount = Integer.parseInt(familySize);
                if (familySizeCount > 4) {
                    clueInitial.setFamilyNum("5人以上");
                } else if (familySizeCount > 2) {
                    clueInitial.setFamilyNum("3-4人");
                } else {
                    clueInitial.setFamilyNum("1-2人");
                }
            }
            //职位--职业
            clueInitial.setVocation(clueLead.getPersontitle());

            // 购买方式 , 购车类型,车辆价格 crm没有不同步
            // 拟购时间 dictionary 表 module=PURCHASE_TIME, 他们的值加上buy_time_为我们的code
            String purchaseTime = clueLead.getPurchaseTime();
            if (!StringUtils.isEmpty(purchaseTime)) {
                clueInitial.setMayBuyTime("buy_time_" + purchaseTime);
            }

            // 线索等级/意向等级  dictionary 表 module=DETAIL_LEAD_LEVEL
            String level = clueLead.getLevel();
            if (!StringUtils.isEmpty(level)) {
                clueInitial.setIntentionGrade("clue_intention_grade_" + level);
            }

            //文化程度 dictionary 表 module=LEAD_EDUCATION_LEVEL
            //字典（1 硕士，2 博士，3 博士后，4 本科，5 大专，，6 初中及以下，7 高中/中专/技校/职高，8 未知）
            String educationLevel = clueLead.getEducationLevel();
            if (!StringUtils.isEmpty(educationLevel)) {
                if ("1".equals(educationLevel)) {
                    clueInitial.setEducation("硕士");
                } else if ("2".equals(educationLevel)) {
                    clueInitial.setEducation("博士");
                } else if ("3".equals(educationLevel)) {
                    clueInitial.setEducation("博士后");
                } else if ("4".equals(educationLevel)) {
                    clueInitial.setEducation("本科");
                } else if ("5".equals(educationLevel)) {
                    clueInitial.setEducation("大专");
                } else if ("6".equals(educationLevel)) {
                    clueInitial.setEducation("初中及以下");
                } else if ("7".equals(educationLevel)) {
                    clueInitial.setEducation("高中/中专/技校/职高");
                } else if ("8".equals(educationLevel)) {
                    clueInitial.setEducation("未知");
                }
            }

            //省，市，区名称
            // provinceName省名称  ,cityName市名称 districtName区域名称转对应的code
            this.getProvinceWithArea(clueLead.getProvinceName(), clueLead.getCityName(), clueLead.getSubcityName(), clueInitial);

            //经销商 dealerCode
            String dealerCode = clueLead.getDealerCode();
            if (!StringUtils.isEmpty(dealerCode)) {
                clueInitial.setDistributeDealerCode(dealerCode);
                DealerResponse dealer = this.getChangeDealer(dealerCode, tenandId, corpId);
                if (dealer != null) {
                    clueInitial.setDealerId(dealer.getId().toString());
                    if (StringUtils.isEmpty(clueInitial.getProvinceCode())) {
                        clueInitial.setProvinceCode(dealer.getProvinceCode());
                    }
                    if (StringUtils.isEmpty(clueInitial.getCityCode())) {
                        clueInitial.setCityCode(dealer.getCityCode());
                    }
                    if (StringUtils.isEmpty(clueInitial.getDistrictCode())) {
                        clueInitial.setDistrictCode(dealer.getDistrictCode());
                    }
                }
            }

            //二级渠道 crm的 is_secondary=1 代表是，0代表否
            String isSecondary = clueLead.getIsSecondary();
            clueInitial.setSourceSecond("1".equals(isSecondary) ? InitialSourceSecondEnum.SOURCE_SECOND_NETWORK.getCode() : InitialSourceSecondEnum.SOURCE_SECOND_DEALER.getCode());
            //如果是二网
            if (!StringUtils.isEmpty(isSecondary) && "1".equals(isSecondary)) {
                //二网公司名称
                String secondName = clueLead.getSecondName();
                // 二网经销商级别  scrm的SECONDARY_SECOND_LEVEL=crm的SECOND_LEVEL
                String secondLevel = clueLead.getSecondLevel();
                //根据 二网公司名称和级别查看是否存在
                SecondaryDealerRequest secodaryReq = new SecondaryDealerRequest();
                secodaryReq.setName(secondName);
                secodaryReq.setLevel("SECONDARY_SECOND_LEVEL_" + secondLevel);
                secodaryReq.setTenantId(tenandId);
                secodaryReq.setCorpId(corpId);
                secodaryReq.setDealerId(Long.valueOf(clueInitial.getDealerId()));
                Response<List<SecondaryDealerResponse>> listResponse = mdQueryClient.getSecondaryDealerByparam(secodaryReq);
                if (listResponse != null && listResponse.getData() != null && listResponse.getData().size() > 0) {
                    SecondaryDealerResponse seRe = listResponse.getData().get(0);
                    clueInitial.setDealerSecondaryId(seRe.getId());

                } else {
                    clueInitial.setDealerSecondaryName(secondName);
                    clueInitial.setDealerSecondaryLevel("SECONDARY_SECOND_LEVEL_" + secondLevel);
                }
            }

            // 跟进人
            String owner = clueLead.getOwner();
            clueInitial.setDistributeEmp(owner);
            this.getChangeEmp(owner, clueInitial);


            List<AddClueIntentionVehicleRequest> addVehicleList = new ArrayList<>();
            //线索源的
            AddClueIntentionVehicleRequest clueInitVeh = new AddClueIntentionVehicleRequest();
            clueInitVeh.setTenantId(tenandId);
            clueInitVeh.setCorpId(corpId);
            clueInitVeh.setDealerId(clueInitial.getDealerId());
            clueInitVeh.setDeleted(DeleteEnum.INIT.getFlag());
            clueInitVeh.setStatus(StatusEnum.TEMP_STOR.getCode());

            //意向车系  ,年款，配置
            String seriesCode = clueLead.getSeriesCode();
           // String modelName = clueLead.getModelName();
          //  String rangeName = clueLead.getRangeName();
            if (!StringUtils.isEmpty(seriesCode)) {
                QueryVehicleSeriesRequest seriesRequest = new QueryVehicleSeriesRequest();
                seriesRequest.setCode(seriesCode);
                seriesRequest.setTenantId(tenandId);
                seriesRequest.setCorpId(corpId);
                //根据车系名称拿到车系id
                Response<VehicleSeriesResponse> seriesRes = mdQueryClient.getOneSeriesByParam(seriesRequest);
                if (seriesRes != null && seriesRes.getData() != null) {
                    VehicleSeriesResponse serRes = seriesRes.getData();
                    clueInitVeh.setSeriesId(serRes.getId().toString());
                    clueInitVeh.setSeriesName(serRes.getName());
                    clueInitVeh.setSeriesCode(serRes.getCode());
                }
            }
            //他们有车系，配置和年款 ,配置和年款拼接就成了车型
            //根据crm年款modelName ，配置name  拿对应的车型id,名称
           /* if (!StringUtils.isEmpty(modelName) && !StringUtils.isEmpty(rangeName)) {
                //根据配置code,年款code,获得配置id
                QueryVehicleModelRequest configRequest = new QueryVehicleModelRequest();
                configRequest.setAnnualModelName(modelName);//年款名称
                configRequest.setConfigName(rangeName);//配置名称
                configRequest.setTenantId(tenandId);
                configRequest.setCorpId(corpId);
                configRequest.setStatus(DeleteEnum.INIT.getFlag());
                Response<VehicleModelResponse> configRes = mdQueryClient.getOneModelByParam(configRequest);
                if (configRes != null && configRes.getData() != null) {
                    VehicleModelResponse vehModel = configRes.getData();
                    clueInitVeh.setModelId(vehModel.getId().toString());
                    clueInitVeh.setModelName(vehModel.getName());
                    clueInitVeh.setModelCode(vehModel.getCode());
                }
            }*/
            addVehicleList.add(clueInitVeh);
            clueInitial.setAddVehicleList(addVehicleList);

            //第二部 创建线索源
            clueInitialManager.insert(clueInitial);
            if (clueInitial.getId() == null) {
                log.error("crmClueId="+clueLead.getCrmClueId()+"的数据入库线索源表失败，没有返回线索源id");
                return;
            }

            Long initialClueId = clueInitial.getId();
            //线索源--意向品牌车系等信息添加
            createInitialClueIntentionVehicle(clueInitial, initialClueId);

            //查看线索表是否有对应的crmClueId数据，若存在，则不入库线索表
            Clue oldClueCheck=new Clue();
            oldClueCheck.setCrmClueId(clueLead.getCrmClueId());
            oldClueCheck.setId(initialClueId);
            Clue clueChekResult= clueService.getOneByParam(oldClueCheck);
            if(clueChekResult!=null) {
                log.error("crmClueId="+clueLead.getCrmClueId()+",线索主键id="+initialClueId+"的数据已在线索表存在，所以不重复入库线索表");
                return;
            }

            //线索源下发--组合线索源下发需要的参数
            ClueFollowUpRequest clueFollowUpRequest = createClueFollowUpRequest(clueInitial);

            //线索下发-参数验证
           /* ClueErrorEnum clueErrorEnum = clueService.checkClueFollowUp(clueFollowUpRequest);
            if (clueErrorEnum != null) {
                log.info("老数据同步，线索源同步到线索池失败，客户phone={}存在活跃线索", clueInitial.getPhone());
                clueLogUpdate.setErrorMessage("crmClueId="+clueLead.getCrmClueId()+"的线索参数验证出错,出错原因="+clueErrorEnum.getMessage()+"所以不入库线索表");
                clueLogUpdate.setStatus(-1);
                clueLogService.updateById(clueLogUpdate);
                return;
            }*/

            //验证oneId对应的客户是否已经存在其它跟进人，若存在则不允许创建线索
           /* String resulStr = clueSyncService.checkOneId(clueFollowUpRequest.getFollowUpCustomer().getOneId(), clueInitial.getDealerId(),
                    clueFollowUpRequest.getFollowUpCustomer().getFollowEmpId(), clueInitial.getTenantId(), clueInitial.getCorpId());
            if (!StringUtils.isEmpty(resulStr)) {
                log.info("老数据同步，线索源同步到线索池失败，客户phone={}已经存在其它跟进人,{}", clueInitial.getPhone(), resulStr);
                clueLogUpdate.setErrorMessage("crmClueId="+clueLead.getCrmClueId()+"的线索参数验证出错,出错原因,客户phone="+clueInitial.getPhone()+"已经存在其它跟进人,"+resulStr);
                clueLogUpdate.setStatus(-1);
                clueLogService.updateById(clueLogUpdate);
                return;
            }*/

            //根据线索下发清洗状态，初始化线索状态  crmLeadStatusChangeFail
            Integer clueStatus = clueService.initClueStatus(clueLead.getLeadStatus());
            if (clueStatus != null) {
                clueFollowUpRequest.getFollowUpClue().setStatus(clueStatus);
            }
            clueFollowUpRequest.getFollowUpClue().setCreatedTime(clueLead.getCreateTime());
            clueFollowUpRequest.getFollowUpClue().setPlanTime(clueLead.getSendTime());
            clueFollowUpRequest.getFollowUpClue().setDealerFollowStatus(clueInitial.getFollowEmpId()==null||clueInitial.getFollowEmpId()==-1?
                    DealerFollowStatusEnum.DISTRIBUTION_DEALER.getCode():DealerFollowStatusEnum.DISTRIBUTION_ADVISER.getCode());
            //初始化客户状态
            clueFollowUpRequest.getFollowUpCustomer().setStatus(CustomerStatusEnum.NORMAL.getCode());
            //初始化codeNameInfo
            //根据渠道code拿对应的渠道名称
            QueryDictionariesRequest hRequest = new QueryDictionariesRequest();
            hRequest.setType("bef_sale_customer_source_third");
            hRequest.setCode(clueInitial.getSourceThird());
            Response<List<DictionariesResponse>> hDicResponse = tenantClient.getDictionariesListByParam(hRequest);
            if (hDicResponse != null && hDicResponse.getData() != null && hDicResponse.getData().size() > 0) {
                DictionariesResponse hDicRes = hDicResponse.getData().get(0);
                codeNameInfo.add(hDicRes == null ? "" : hDicRes.getName());//渠道名称
            }
            // codeNameInfo.add(clueInitial.getSourceThird());//渠道名称
            //根据活动code拿对应的活动名称 bef_sale_customer_source_activity_id
            QueryDictionariesRequest request = new QueryDictionariesRequest();
            request.setType("bef_sale_customer_source_activity_id");
            request.setCode(clueInitial.getSourceActivityId());
            Response<List<DictionariesResponse>> dicResponse = tenantClient.getDictionariesListByParam(request);
            if (dicResponse != null && dicResponse.getData() != null && dicResponse.getData().size() > 0) {
                DictionariesResponse dicRes = dicResponse.getData().get(0);
                codeNameInfo.add(dicRes == null ? "" : dicRes.getName());//活动名称
            }
            codeNameInfo.add(clueInitial.getEducation());
            codeNameInfo.add(clueInitial.getMarriage());
            codeNameInfo.add(clueInitial.getFamilyNum());
            codeNameInfo.remove("");
            codeNameInfo.remove(null);
            clueFollowUpRequest.setCodeNameInfo(JSON.toJSONString(codeNameInfo));

            //线索源下发--企微新增线索源 默认直接进行线索下发,获取线索id
            Long clueId = clueService.createClueWithfollowUp(clueFollowUpRequest, InitalSendTypeEnum.SEND_TYPE_OLD_DATA_SYNC.getCode());
            if(clueId!=null){
                commRedisDao.sAdd(syncLeadTriggerRecord,clueLead.getCrmClueId());
            }
            //线索源下发--线索下发获取线索id后异步执行后续信息(线索的意向信息,意向品牌列表，计划跟进,跟进记录，宽表)
            clueSyncService.createClueWithfollowUpSync(clueFollowUpRequest, InitalSendTypeEnum.SEND_TYPE_OLD_DATA_SYNC.getCode());

    }

    /**
     * 线索源入库线索池测试
     * @param
     */
    @Override
    public void syncInsertClueTest(String crmCLueId,Integer leadStatus) {
        //根据线索源id查看线索；
        //先查看线索源表里是否有对应的crmClueId对应的数据，若存在不入库线索源表
        ClueInitial checkRequest=new ClueInitial();
        checkRequest.setCrmClueId(crmCLueId);
        ClueInitial initial=this.getOneclueInitialByParam(checkRequest);
        if(initial!=null) {
            Long initialClueId=initial.getId();
            //线索源--意向品牌车系等信息添加
            createInitialClueIntentionVehicle(initial,initialClueId);

            //线索源下发--组合线索源下发需要的参数
            ClueFollowUpRequest clueFollowUpRequest=createClueFollowUpRequest(initial);
            //根据线索下发清洗状态，初始化线索状态  crmLeadStatusChangeFail
            Integer clueStatus = clueService.initClueStatus(leadStatus);
            if (clueStatus != null) {
                clueFollowUpRequest.getFollowUpClue().setStatus(clueStatus);
            }

            //线索下发-参数验证
            ClueErrorEnum clueErrorEnum = clueService.checkClueFollowUp(clueFollowUpRequest);
            if (clueErrorEnum != null) {
                throw new BusinessException(clueErrorEnum);
            }

            //验证oneId对应的客户是否已经存在其它跟进人，若存在则不允许创建线索
            String resulStr = clueSyncService.checkOneId(clueFollowUpRequest.getFollowUpCustomer().getOneId(), initial.getDealerId(),
                    clueFollowUpRequest.getFollowUpCustomer().getFollowEmpId(),initial.getTenantId(),initial.getCorpId());
            if (!StringUtils.isEmpty(resulStr)) {
                throw new BusinessException("该客户已经存在其它跟进人，" + resulStr);
            }
            //线索源下发--企微新增线索源 默认直接进行线索下发,获取线索id

            Long  clueId=clueService.createClueWithfollowUp(clueFollowUpRequest, InitalSendTypeEnum.SEND_TYPE_QW.getCode());
            //线索源下发--线索下发获取线索id后异步执行后续信息(线索的意向信息,意向品牌列表，计划跟进,跟进记录，宽表)
            clueSyncService.createClueWithfollowUpSync(clueFollowUpRequest,InitalSendTypeEnum.SEND_TYPE_QW.getCode());
        }
    }
}
